﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSIExtracter.Commands;
using System.Diagnostics;
using System.IO;
using MSIExtracter.Data;
using System.Collections.ObjectModel;

namespace MSIExtracter.ViewModel
{
    public class MainWindowViewModel:ViewModelBase
    {
        public RelayCommand ExtractCommand { get; set; }

        private string _statusMsg;

        public string StatusMsg
        {
            get
            {
                return _statusMsg;
            }
            set
            {
                _statusMsg = value;
                OnNotifyPropertyChanged("StatusMsg");
            }
        }

        private ObservableCollection<DirectoryRecord> _targetLoc;

        public ObservableCollection<DirectoryRecord> TargetLoc 
        { 
            get
            {
                return _targetLoc;
            }
            set
            {
                _targetLoc = value;
                OnNotifyPropertyChanged("TargetLoc");
            }
        }



        public MainWindowViewModel()
        {
            ExtractCommand = new RelayCommand(canExtract, Extract);
        }

        private bool canExtract(object param)
        {
            return true;
        }

        private string targetpath = string.Empty;

        private void Extract(object param)
        {
            StatusMsg = string.Empty;

            var values = (object[])param; 
            string msipath = (string)values[0];
            targetpath = (string)values[1];

            if (string.IsNullOrWhiteSpace(msipath) || string.IsNullOrWhiteSpace(targetpath))
            {
                StatusMsg = "Path field should not be empty. Please enter the valid path";
                return;
            }
            else if(Path.GetExtension(msipath) == ".msi" || !File.Exists(msipath))
            {
                StatusMsg = "The mentioned msi file path is not valid. Please enter the valid file path";
                return;
            }

            ProcessStartInfo start = new ProcessStartInfo(); 
            start.FileName = @"msiexec.exe"; 
            start.UseShellExecute = false;     
            start.RedirectStandardOutput = true;
            start.CreateNoWindow = true;
            start.WindowStyle = ProcessWindowStyle.Hidden;
            start.Arguments = string.Format("/a \"{0}\" /qb  TARGETDIR=\"{1}\"",msipath, targetpath);

            Process process = new Process();
            process.EnableRaisingEvents = true;
            process.Exited += new EventHandler(process_Exited);
            process.StartInfo = start;
            process.Start();
           
        }

        void process_Exited(object sender, EventArgs e)
        {
            TargetLoc = new ObservableCollection<DirectoryRecord> { new DirectoryRecord { Info = new DirectoryInfo(targetpath) } };
        }
    }
}
